/**
 * 导入相关框架框架
 */
import express from "express";
import glob from "glob";
import path from "path";
const app = express();

/**
 * 解析,用req.body获取post参数
 */
import bodyParser from "body-parser";
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

/**
 * 解析token
 */
import { jwtSecretKey } from "./src/config/token";
import expressJWT from "express-jwt";
app.use(expressJWT({ secret: jwtSecretKey, requestProperty: 'auth', algorithms: ["HS256"] }).unless({ path: ["/user/code", "/user/login", "/user/register"] }));

/**
 * 错误中间件
 */
app.use(function (err: Error, req: any, res: any, next: any) {
    if (err.name === 'UnauthorizedError') return res.status(401).send('身份认证失败！');
})

/**
 * 自动遍历项目数  遍历成接口方法
 */
glob(path.join(__dirname, '/src/controller/**/*.js'), {}, (err, files: string[]) => {
    files.forEach(file => {
        const instance = require(file);
        const rootUrl = __dirname.replace(/\\/g, '/');
        const urlPath = file.replace(rootUrl + '/src/controller', '').replace(/\.[^.]*$/g, '');
        const methods = Object.keys(instance);
        methods.forEach(method => {
            if (method == 'validator') return;
            const validator = instance['validator'] || [];
            app[method.toLowerCase()](urlPath, validator, instance[method]);
        });
    })
})

app.listen(3000, () => {
    console.log("服务端口已启动，地址：http://localhost:3000/");
})